package com.ss.test09;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Auther: 520ljs
 * @Date: 2022/3/19 - 03 - 19 - 22:23
 */
public class BuyTicketThread05 implements Runnable{
    int ticketNum = 10;

    //拿来一把锁：
    Lock lock = new ReentrantLock();
    @Override
    public void run() {
        for (int i = 1; i <= 100; i++){
         //打开锁：
         lock.lock();
         try{
             if(ticketNum > 0){
                 System.out.println("我在"+Thread.currentThread().getName() + "买到了背景到哈尔滨的第"+ticketNum--+"张车票");
             }
         }catch (Exception ex){
             ex.printStackTrace();
         }finally{
             //关闭锁：--->即使有异常，这个锁也可以得到释放
             lock.unlock();
         }
        }
    }
}
